﻿using KimPhongCRM.Models;
using System;
using System.Collections;
using System.Xml;
using Joshi.Utils.Imap;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using System.Net;
using System.IO;


namespace KimPhongCRM.Lib
{
    public static class NetUtils
    {
        public static bool SendEmailOld(string subject, string content, Dictionary<string, string> emailConfig)
        {
            try
            {
                /*====================================================================================================*/
                /*
                 * fAddress = From fAddress
                 * fDisplayName = From DisplayName
                 * tAddress = To Address
                 * tDisplayName = To DisplayName
                 * tsAddress = To Second Address
                 * tsDisplayName = To Second DisplayName
                 * host = eg : smtp.gmail.com
                 * port = eg : 587
                 * userName = user name ,eg : ngocdien.tk@gmail.com
                 * passWord = pass of email userName
                 */
                /*====================================================================================================*/
                var value = emailConfig["fAddress"];
                MailAddress mailAddFrom = new MailAddress("khohd.com@gmail.com", "KhoHD.COM");
                MailAddress mailAddTo = new MailAddress("khohd.hung@yahoo.com.vn", "Quản trị website khohd.com");
                MailAddress mailTo2 = new MailAddress("tienngang@3tmedia.vn", "Quản trị website khohd.com");
                MailMessage mail = new MailMessage(mailAddFrom, mailAddTo);
                mail.To.Add(mailTo2);
                mail.Subject = subject;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.UTF8;// put subject here	
                mail.Body = content;
                SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential("khohd.com@gmail.com", "Khoquadi_)(8611");
                smtp.Send(mail);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool SendEmail(string subject, string content, tblEmailConfig config)
        {
            try
            {
                /*====================================================================================================*/
                /*
                 * fAddress = From fAddress
                 * fDisplayName = From DisplayName
                 * tAddress = To Address
                 * tDisplayName = To DisplayName
                 * tsAddress = To Second Address
                 * tsDisplayName = To Second DisplayName
                 * host = eg : smtp.gmail.com
                 * port = eg : 587
                 * userName = user name ,eg : ngocdien.tk@gmail.com
                 * passWord = pass of email userName
                 */
                /*====================================================================================================*/
                MailAddress mailAddFrom = new MailAddress(config.fAddress, config.fDisplayName);
                MailAddress mailAddTo = new MailAddress(config.tAddress, config.tDisplayName);
                MailAddress mailTo2 = new MailAddress(config.tsAddress,config.tsDisplayName);
                MailMessage mail = new MailMessage(mailAddFrom, mailAddTo);
                mail.To.Add(mailTo2);
                mail.Subject = subject;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.UTF8;// put subject here	
                mail.Body = content;
                SmtpClient smtp = new SmtpClient(config.host, Convert.ToInt32(config.port));
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(config.userName, config.passWord);
                smtp.Send(mail);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static List<Dictionary<string, string>> reCeive(tblEmailConfig eConfig)
        {
            List<Dictionary<string, string>> listEmail = new List<Dictionary<string, string>>();

            WebRequest webGmailRequest = WebRequest.Create(@"https://mail.google.com/mail/feed/atom");
            webGmailRequest.PreAuthenticate = true;

            NetworkCredential loginCredentials = new NetworkCredential(eConfig.userName, eConfig.passWord);
            webGmailRequest.Credentials = loginCredentials;

            WebResponse webGmailResponse = webGmailRequest.GetResponse();
            Stream strmUnreadMailInfo = webGmailResponse.GetResponseStream();

            StringBuilder sbUnreadMailInfo = new StringBuilder(); byte[] buffer = new byte[8192]; int byteCount = 0;

            while ((byteCount = strmUnreadMailInfo.Read(buffer, 0, buffer.Length)) > 0)
                sbUnreadMailInfo.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, byteCount));//ASCII

            XmlDocument UnreadMailXmlDoc = new XmlDocument();
            UnreadMailXmlDoc.LoadXml(sbUnreadMailInfo.ToString());
            XmlNodeList UnreadMailEntries = UnreadMailXmlDoc.GetElementsByTagName("entry");

            //UnreadMails oUnreadMails = new UnreadMails();
            //Collection<UnreadMails> clUnreadMails = new Collection<UnreadMails>();

            for (int _i = 0; _i < UnreadMailEntries.Count; ++_i)
            {
                string fromEmail = (UnreadMailEntries[_i]["author"])["email"].InnerText.ToString();
                if (fromEmail.Contains(eConfig.tAddress) || fromEmail.Contains(eConfig.tsAddress))
                {               
                    Dictionary<string, string> email = new Dictionary<string, string>();
                    email.Add("Subject", UnreadMailEntries[_i]["title"].InnerText.ToString());
                    email.Add("Content", UnreadMailEntries[_i]["summary"].InnerText.ToString());
                    email.Add("From", (UnreadMailEntries[_i]["author"])["name"].InnerText.ToString());
                    email.Add("FromEmail", (UnreadMailEntries[_i]["author"])["email"].InnerText.ToString());
                    email.Add("MailModify", UnreadMailEntries[_i]["modified"].InnerText.ToString());
                    listEmail.Add(email);
                }
             }

            return listEmail;
        }
    }
}